package com.gnerv.cms.config;

import com.gnerv.cms.freemarker.FreemarkerComponent;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/3/18
 */
@Component
public class FreemarkerConfig implements ApplicationContextAware {

    ApplicationContext applicationContext;

    @Resource
    Configuration configuration;

    @PostConstruct
    public void setSharedVariable() throws IOException, TemplateException {
        // 根据注解获取bean ,key is bean name ,value is bean object
        Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(
                FreemarkerComponent.class);
        for (String key : map.keySet()) {
            configuration.setSharedVariable(key, map.get(key));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
